package jp.co.cos.ittrick.channel.controller.admin;

import java.util.ArrayList;
import java.util.List;

import jp.co.cos.ittrick.channel.model.ChapterModel;
import jp.co.cos.ittrick.channel.model.PageModel;
import jp.co.cos.ittrick.channel.service.ChapterService;
import jp.co.cos.ittrick.channel.service.PageService;

import org.slim3.controller.Controller;
import org.slim3.controller.Navigation;

import com.google.appengine.api.datastore.Text;

public class PageInsertController extends Controller {

    private PageService pageService;
    private ChapterService chapterService;

    public PageInsertController() {
        pageService = new PageService();
        chapterService = new ChapterService();
    }

    @Override
    public Navigation run() throws Exception {

        // リクエストパラメータ
        String channel = asString("channel");
        String chapter = asString("chapter");
        String name = asString("pageName");
        String index = asString("index");
        String content = asString("content");
        String keyWords = asString ("keyWordList");
        String description = asString("description");

        List<String> keyWordList = getStringList(keyWords);

        ChapterModel chapterModel = chapterService.getChapterByKey(Integer.valueOf(chapter));

        // Modelの設定
        PageModel model = new PageModel();
        model.setName(name);
        model.setIndex(Integer.valueOf(index));
        model.setKeyWordList(keyWordList);
        model.setDescription(description);
        model.getChapterModelRef().setModel(chapterModel);
        model.setContent(new Text(content));

        // Insert
        pageService.insert(model);

        return redirect("/admin/channel?channel=" + channel);
    }


    private List<String> getStringList(String texts) {

        List<String> stringList = new ArrayList<String>();
        if(texts != null && texts != "") {
            String[] amznWdgtAsinsTmp = texts.split(",");
            for(String txt: amznWdgtAsinsTmp) {
                if(!txt.isEmpty()) {
                    stringList.add(txt);
                }
            }
        }
        return stringList;
    }

}
